package com.ibeetl.cms.web;

import com.alibaba.fastjson.JSON;
import com.ibeetl.admin.core.util.AESMacUtil;
import com.ibeetl.admin.core.util.AESUtil;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.*;
import com.ibeetl.cms.service.*;
import com.ibeetl.cms.util.ProcessConstant;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.validation.SmartValidator;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author qianduan
 */
@Service
public class PretrialService {

    private final Log log = LogFactory.getLog(this.getClass());

    @Autowired
    private IndustrialTalentsService industrialTalentsService;

    @Autowired
    private BuyHouseSubsidiesService buyHouseSubsidiesService;

    @Autowired
    private SkillService skillService;

    @Autowired
    private ProfessionalTechnologyService professionalTechnologyService;
    @Autowired
    private RentingService rentingService;
    @Autowired
    private OutboundSubsidyService outboundSubsidyService;
    @Autowired
    private DoctoralSubsidyService doctoralSubsidyService;
    @Autowired
    private HighlevelTalentsService highlevelTalentsService;

    @Autowired
    private SmartValidator validator;

    @Autowired
    private TelentCardService telentCardService;

    @Autowired
    private InvokeLogService invokeLogService;

    @Autowired
    Environment env;


    /**
     * 审核结果内容，格式为
     * {"id": "1","result": "1","approvalAmount": "1000","approvalAmountUnit": "元","opinion":"同意","isSendMessage":"1"}
     * Id为业务数据的id，必填
     * result的值如下：必填
     * 0:通过
     * 1:退回
     * 2:终止
     * approvalAmount为审批金额,必填
     * approvalAmountUnit为审批金额单位  元或者万元,必填
     * opinion为审批意见，必填
     * isSendMessage为是否发送短信，必填，1为发送，0为不发送
     * @param type 申报信息的类型，看下列表格
     * @param id
     * @param result
     * @param approvalAmount
     * @param approvalAmountUnit
     * @param opinion
     * @param isSendMessage
     */
    public boolean post(int type, String id,
                        String result,
                        String approvalAmount,
                        String approvalAmountUnit,
                        String opinion,
                        String isSendMessage) {
        String external_url = env.getProperty("external_url");

        boolean postResult = false;
        final String PWD = "mc-talentLicense";


        /**
         * 默认为元
         */
        if ("".equalsIgnoreCase(approvalAmountUnit)) {
            approvalAmountUnit = "元";
        }

        /**
         * 默认为0
         */
        if ("".equalsIgnoreCase(approvalAmount)) {
            approvalAmount = "0";
        }
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(external_url);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("type", String.valueOf(type)));

        Pretrial pretrial = new Pretrial();
        pretrial.setId(id);
        pretrial.setResult(result);
        pretrial.setApprovalAmount(approvalAmount);
        pretrial.setApprovalAmountUnit(approvalAmountUnit);
        pretrial.setOpinion(opinion);
        pretrial.setIsSendMessage(isSendMessage);
        String pretrialJson = JSON.toJSONString(pretrial);
        String message = AESMacUtil.encrypt(pretrialJson, PWD);
        log.debug(message);
        params.add(new BasicNameValuePair("message", message));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            CloseableHttpResponse response = null;
            response = client.execute(httpPost);

            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String resResult = null;

                    resResult = EntityUtils.toString(resEntity, "utf-8");

                    JsonResult jsonResult = JSON.parseObject(resResult, JsonResult.class);
                    invokeLog(type, message, pretrialJson, jsonResult.getCode().equalsIgnoreCase("0"), "pretrialService.post");
                    if (jsonResult.getCode().equalsIgnoreCase("0")) {
                        postResult = true;
                        /**
                         * 成功的情况
                         * 关于状态的修改，是在原来的代码上修改
                         */
                        switch (type) {
                            case 1:
                                PageQuery<IndustrialTalents> pageQuery = new PageQuery<>();
                                pageQuery.setPara("externalTaskId", id);
                                PageQuery<IndustrialTalents> industrialTalentsPageQuery = industrialTalentsService.queryByCondition(pageQuery);
                                List<IndustrialTalents> industrialTalentsList = industrialTalentsPageQuery.getList();
                                if (industrialTalentsList.size() > 0) {
                                    IndustrialTalents industrialTalents = industrialTalentsList.get(0);
                                    industrialTalents.setInvokeStatus("true");
                                    boolean success = industrialTalentsService.updateTemplate(industrialTalents);
                                }
                                break;
                            case 2:
                                PageQuery<BuyHouseSubsidies> houseSubsidiesPageQuery = new PageQuery<>();
                                houseSubsidiesPageQuery.setPara("externalTaskId", id);
                                PageQuery<BuyHouseSubsidies> buyHouseSubsidiesPageQuery = buyHouseSubsidiesService.queryByCondition(houseSubsidiesPageQuery);
                                List<BuyHouseSubsidies> buyHouseSubsidiesList = buyHouseSubsidiesPageQuery.getList();
                                if (buyHouseSubsidiesList.size() > 0) {
                                    BuyHouseSubsidies buyHouseSubsidies = buyHouseSubsidiesList.get(0);
                                    buyHouseSubsidies.setInvokeStatus("true");
                                    boolean success = buyHouseSubsidiesService.updateTemplate(buyHouseSubsidies);
                                }
                                break;
                            case 3:
                                PageQuery<Skill> skillPageQuery1 = new PageQuery<>();
                                skillPageQuery1.setPara("externalTaskId", id);
                                PageQuery<Skill> skillPageQuery = skillService.queryByCondition(skillPageQuery1);
                                List<Skill> skillList = skillPageQuery.getList();
                                if (skillList.size() > 0) {
                                    Skill skill = skillList.get(0);
                                    skill.setInvokeStatus("true");
                                    boolean success = skillService.updateTemplate(skill);
                                }
                                break;
                            case 4:
                                PageQuery<ProfessionalTechnology> professionalTechnologyPageQuery1 = new PageQuery<>();
                                professionalTechnologyPageQuery1.setPara("externalTaskId", id);
                                PageQuery<ProfessionalTechnology> professionalTechnologyPageQuery = professionalTechnologyService.queryByCondition(professionalTechnologyPageQuery1);
                                List<ProfessionalTechnology> professionalTechnologyList = professionalTechnologyPageQuery.getList();
                                if (professionalTechnologyList.size() > 0) {
                                    ProfessionalTechnology professionalTechnology = professionalTechnologyList.get(0);
                                    professionalTechnology.setInvokeStatus("true");
                                    boolean success = professionalTechnologyService.updateTemplate(professionalTechnology);
                                }
                                break;
                            case 5:
                                PageQuery<Renting> rentingPageQuery1 = new PageQuery<>();
                                rentingPageQuery1.setPara("externalTaskId", id);
                                PageQuery<Renting> rentingPageQuery = rentingService.queryByCondition(rentingPageQuery1);
                                List<Renting> rentingList = rentingPageQuery.getList();
                                if (rentingList.size() > 0) {
                                    Renting renting = rentingList.get(0);

                                    renting.setInvokeStatus("true");

                                    boolean success = rentingService.updateTemplate(renting);
                                }
                                break;
                            case 6:
                                PageQuery<DoctoralSubsidy> doctoralSubsidyPageQuery1 = new PageQuery<>();
                                doctoralSubsidyPageQuery1.setPara("externalTaskId", id);
                                PageQuery<DoctoralSubsidy> doctoralSubsidyPageQuery = doctoralSubsidyService.queryByCondition(doctoralSubsidyPageQuery1);
                                List<DoctoralSubsidy> doctoralSubsidyList = doctoralSubsidyPageQuery.getList();
                                if (doctoralSubsidyList.size() > 0) {
                                    DoctoralSubsidy doctoralSubsidy = doctoralSubsidyList.get(0);
                                    doctoralSubsidy.setInvokeStatus("true");

                                    boolean success = doctoralSubsidyService.updateTemplate(doctoralSubsidy);
                                }
                                break;
                            case 7:
                                PageQuery<OutboundSubsidy> outboundSubsidyPageQuery1 = new PageQuery<>();
                                outboundSubsidyPageQuery1.setPara("externalTaskId", id);
                                PageQuery<OutboundSubsidy> outboundSubsidyPageQuery = outboundSubsidyService.queryByCondition(outboundSubsidyPageQuery1);
                                List<OutboundSubsidy> outboundSubsidyList = outboundSubsidyPageQuery.getList();
                                if (outboundSubsidyList.size() > 0) {
                                    OutboundSubsidy outboundSubsidy = outboundSubsidyList.get(0);


                                    outboundSubsidy.setInvokeStatus("true");

                                    boolean success = outboundSubsidyService.updateTemplate(outboundSubsidy);
                                }
                                break;
                            case 8:
                                PageQuery<HighlevelTalents> highlevelTalentsPageQuery1 = new PageQuery<>();
                                highlevelTalentsPageQuery1.setPara("externalTaskId", id);
                                PageQuery<HighlevelTalents> highlevelTalentsPageQuery = highlevelTalentsService.queryByCondition(highlevelTalentsPageQuery1);
                                List<HighlevelTalents> highlevelTalentsList = highlevelTalentsPageQuery.getList();
                                if (highlevelTalentsList.size() > 0) {
                                    HighlevelTalents highlevelTalents = highlevelTalentsList.get(0);

                                    highlevelTalents.setInvokeStatus("true");

                                    boolean success = highlevelTalentsService.updateTemplate(highlevelTalents);
                                }
                                break;
                        }
                    } else {
                        /**
                         * 失败的情况
                         */
                        postResult = false;

                    }
                }
            }

            client.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return postResult;
    }


    private void invokeLog(int type, String message, String decodeMessage, Boolean result, String method) {
        try {
            InvokeLog invokeLog = new InvokeLog();
            invokeLog.setType(type);
            invokeLog.setMessage(message);
            invokeLog.setDecodeMessage(decodeMessage);
            invokeLog.setResult(result.toString());
            invokeLog.setMethod(method);
            invokeLog.setInvokeTime(new Date());
            invokeLogService.save(invokeLog);
        } catch (Exception e) {
            log.error("log error: " + e.getMessage());
        }

    }
}
